package com.async.demo.controller;

import com.async.demo.model.DeferredResultHolder;
import com.async.demo.model.MockQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * @author Administrator
 */
@Slf4j
@RestController
public class AsyncController {


    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;
    /**
     *  同步请求
     * @return
     * @throws Exception
     */
    @RequestMapping("/order")
    public String order() throws  Exception{
        log.info("主线程开始");
        Thread.sleep(1000);
        log.info("主线程返回");
        return "success";
    }

    /**
     *  异步请求
     *   - 增加吞吐量
     * @return
     */
    @RequestMapping("/callableOrder")
    public Callable<String> callableOrder() throws InterruptedException {
        log.info("主线程开始");
        // 单开一个线程
        Callable<String> result = () -> {
            log.info("副线程开始");
            Thread.sleep(10000);
            log.info("副线程返回");
            return "success";
        };

        log.info("主线程返回");
        return result;
    }

    /**
     *  异步请求
     *   - 增加吞吐量
     * @return
     */
    @RequestMapping("/deferResult")
    public DeferredResult<String> deferResult() throws InterruptedException {
        log.info("主线程开始");
        // 单开一个线程
        String orderNumber = UUID.randomUUID().toString();
        mockQueue.setPlaceOrder(orderNumber);
        DeferredResult<String> result = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNumber,result);
        log.info("主线程返回");
        return result;
    }


}
